/* ----------------------------------------------------------------------------------------------------------------
 * ImageSection
 * ----------------------------------------------------------------------------------------------------------------
 */
package pure.engine.renderer.sections 
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.utils.getDefinitionByName;
	import pure.engine.renderer.RenderUtil;
	import pure.engine.system.SystemManager;
	
	import pure.engine.system.ns_despair;
	
	use namespace ns_despair;
	
	/**
	 * @internal
	 * 
	 * Image型片段
	 * @author ＃Pure
	 * 
	 * ＃适合制作简单型渲染模型
	 */
internal final class ImageSection extends Section 
{
	public function ImageSection(name:String,source:*, x:Number, y:Number, width:Number, height:Number, realRect:Rectangle)
	{
		super(name,source, x, y, realRect);
		
		cachedRect = new Rectangle(0, 0, width, height);
	}


	
	
	protected var _image:BitmapData;
	protected var _numImagePerRow:int;
	
	protected var cachedRect:Rectangle;
	protected static var cachedPoint:Point = new Point();
	
	
	
	
	override protected function _parseAssets(source:*):void 
	{
		var obj:Class;
		
		if (source is String)
		{
            obj = SystemManager.getDefinition(source);
            if(!obj)
            {
                throw new Error('[ImageSection] - ＃_parseAssets - 资源 (' + source + ') 不存在.');
            }
            _image = new obj();
		}
		else
		{
			_image = source;
		}
		
		var numCol:Number = _image.width / m_width;
		var numRow:Number = _image.height / m_height;
		
		if (numCol is int && numRow is int)
		{
			m_maxLength = numCol * numRow * 2 + 1;
			m_bitmaps = new Vector.<BitmapData>(m_maxLength);
			_numImagePerRow = numCol;
		}
		else
		{
			throw new Error('ImageSection - ＃loadAssets - Image data has an error.');
		}
	}

	
	override protected function _preDraw(pointer:int):void
	{
		var bitmapData:BitmapData = new BitmapData(m_width, m_height, true, 0x0);
		
		// 正向绘制
		if (pointer > 0) 
		{
			cachedRect.x = (pointer - 1) % _numImagePerRow * m_width;
			cachedRect.y = int((pointer - 1) / _numImagePerRow) * m_height;
			bitmapData.copyPixels(_image, cachedRect, cachedPoint,null,null,true);
			m_bitmaps[pointer] = bitmapData;
		}
		
		// 反向绘制
		else if (pointer < 0)
		{
			var tmpPointer:int = this.m_maxLength + pointer;
			var frame:int = ~pointer + 1;
			cachedRect.x = (frame - 1) % _numImagePerRow;
			cachedRect.y = int((frame - 1) / _numImagePerRow);
			bitmapData.copyPixels(_image, cachedRect, cachedPoint);
			
			bitmapData = RenderUtil.createBitmapByDisplay(bitmapData, m_width,m_height, true);
			m_bitmaps[tmpPointer] = bitmapData;
		}
		
		else 
		{
			throw new Error(" 片段指针不可为0");
		}
	}

}

}